package com.bestcem.xm.common.core.config.grpc;

import io.grpc.*;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * 自定义grpc连接channel
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/15 21:59
 */
@Slf4j
public class XMManagedChannel extends Channel {

    private String name;

    private List<ClientInterceptor> interceptors;

    private boolean sortInterceptors;

    private XmGrpcFactory delegate;

    public static DelayQueue<DelayedChannel> closeQueue = new DelayQueue<>();

    static {
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        DelayedChannel channel = closeQueue.take();
                        channel.getManagedChannel().shutdown();
                    } catch (InterruptedException e) {
                        log.error("[grpc] grpc定时关闭channel异常", e);
                    }
                }

            }
        }.start();
    }



    public XMManagedChannel(XmGrpcFactory delegate, String name, List<ClientInterceptor> interceptors, boolean sortInterceptors) {
        this.delegate = delegate;
        this.name = name;
        this.interceptors = interceptors;
        this.sortInterceptors = sortInterceptors;
    }

    @Override
    public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
        Channel[] channels = delegate.xmCreateChannel(name, interceptors, sortInterceptors);
        ClientCall<RequestT, ResponseT> requestTResponseTClientCall = channels[1].newCall(methodDescriptor, callOptions);
        closeQueue.put(new DelayedChannel((ManagedChannel) channels[0], 1000L));
        return requestTResponseTClientCall;
    }

    @Override
    public String authority() {
        return name;
    }


}
